from datetime import datetime
from typing import TYPE_CHECKING

from config.logging_config import get_logger

if TYPE_CHECKING:
    from AIAgents.model.NavigationAgent import NavigationAgentState

from navigation.saveNavigation import NavigationSaveService

# 设置日志记录器
logger = get_logger(__name__)


def execute_tools_node(agent, state: 'NavigationAgentState') -> 'NavigationAgentState':
    """执行工具调用 - 使用BaseAgent的_execute_tool_action方法"""
    logger.info("🔧 执行工具调用")

    try:
        if not agent.tools:
            logger.warning("⚠️ 没有可用的工具")
            return state

        # 获取解析后的action参数
        action_params = state.get("intelligent_response", {})
        tool_name = action_params.get("tool_name")
        tool_params = action_params.get("tool_params", {})
        reasoning = action_params.get("reasoning", "")

        if not tool_name:
            logger.error("❌ 工具名称为空")
            tool_result = {
                "tool_name": "unknown",
                "error": "工具名称为空",
                "success": False,
                "timestamp": datetime.now().isoformat()
            }
            state["tool_results"] = state.get("tool_results", [])
            state["tool_results"].append(tool_result)
            return state

        # 构造符合BaseAgent期望的解析响应格式
        parsed_response = {
            "tool_name": tool_name,
            "tool_params": tool_params,
            "reasoning": reasoning
        }

        # 构建上下文
        context = {
            "input": state.get("input", ""),
            "current_thought": state.get("current_thought", ""),
            "rag_results": state.get("rag_results", [])
        }

        # 调用BaseAgent的工具执行方法
        execution_result = agent._execute_tool_action(parsed_response, context)

        # 转换为NavigationAgent的结果格式
        if execution_result.get("success", False):
            tool_result = {
                "tool_name": execution_result.get("tool_name"),
                "params": execution_result.get("tool_params", {}),
                "result": execution_result.get("tool_result"),
                "reasoning": execution_result.get("reasoning", ""),
                "success": True,
                "timestamp": datetime.now().isoformat()
            }
            logger.info(f"✅ 工具执行成功: {tool_result['tool_name']}")
        else:
            tool_result = {
                "tool_name": execution_result.get("tool_name", "unknown"),
                "error": execution_result.get("error", "工具执行失败"),
                "success": False,
                "timestamp": datetime.now().isoformat()
            }
            logger.error(f"❌ 工具执行失败: {tool_result['error']}")

        # 添加到状态
        state["tool_results"] = state.get("tool_results", [])
        state["tool_results"].append(tool_result)

        # 将工具结果保存到当前执行记忆中
        agent._save_result_to_memory("tool", tool_result, state)

    except Exception as e:
        logger.error(f"❌ 工具执行失败: {str(e)}")
        tool_result = {
            "tool_name": "unknown",
            "error": str(e),
            "success": False,
            "timestamp": datetime.now().isoformat()
        }
        state["tool_results"] = state.get("tool_results", [])
        state["tool_results"].append(tool_result)

    return state


def execute_mcp_node(agent, state: 'NavigationAgentState') -> 'NavigationAgentState':
    """执行MCP调用 - 使用BaseAgent的_execute_mcp_action方法"""
    logger.info("🔌 执行MCP调用")

    try:
        # 获取解析后的action参数
        action_params = state.get("intelligent_response", {})
        server_name = action_params.get("server_name")
        tool_name = action_params.get("tool_name")
        mcp_params = action_params.get("mcp_params", {})
        reasoning = action_params.get("reasoning", "")

        if not server_name:
            logger.error("❌ MCP服务名称为空")
            mcp_result = {
                "server_name": "unknown",
                "tool_name": tool_name or "unknown",
                "error": "MCP服务名称为空",
                "success": False,
                "timestamp": datetime.now().isoformat()
            }
            state["mcp_results"] = state.get("mcp_results", [])
            state["mcp_results"].append(mcp_result)
            return state

        # 构造符合BaseAgent期望的解析响应格式
        parsed_response = {
            "server_name": server_name,
            "tool_name": tool_name,
            "mcp_params": mcp_params,
            "reasoning": reasoning
        }

        # 构建上下文
        context = {
            "input": state.get("input", ""),
            "current_thought": state.get("current_thought", ""),
            "rag_results": state.get("rag_results", [])
        }

        # 调用BaseAgent的MCP执行方法
        execution_result = agent._execute_mcp_action(parsed_response, context)

        # 转换为NavigationAgent的结果格式
        if execution_result.get("success", False):
            mcp_result = {
                "server_name": execution_result.get("server_name"),
                "tool_name": execution_result.get("tool_name"),
                "params": execution_result.get("mcp_params", {}),
                "result": execution_result.get("mcp_result"),
                "reasoning": execution_result.get("reasoning", ""),
                "success": True,
                "timestamp": datetime.now().isoformat()
            }
            logger.info(f"✅ MCP执行成功: {mcp_result['server_name']}")
        else:
            mcp_result = {
                "server_name": execution_result.get("server_name", "unknown"),
                "tool_name": execution_result.get("tool_name", "unknown"),
                "error": execution_result.get("error", "MCP执行失败"),
                "success": False,
                "timestamp": datetime.now().isoformat()
            }
            logger.error(f"❌ MCP执行失败: {mcp_result['error']}")

        # 添加到状态
        state["mcp_results"] = state.get("mcp_results", [])
        state["mcp_results"].append(mcp_result)

        # 将MCP结果保存到当前执行记忆中
        agent._save_result_to_memory("mcp", mcp_result, state)

    except Exception as e:
        logger.error(f"❌ MCP执行失败: {str(e)}")
        mcp_result = {
            "server_name": "unknown",
            "tool_name": "unknown",
            "error": str(e),
            "success": False,
            "timestamp": datetime.now().isoformat()
        }
        state["mcp_results"] = state.get("mcp_results", [])
        state["mcp_results"].append(mcp_result)

    return state


def execute_rag_node(agent, state: 'NavigationAgentState') -> 'NavigationAgentState':
    """执行导航查询 - 从数据库查询相关导航信息"""
    logger.info("🔍 执行导航查询")

    try:
        # 解析查询参数
        query_text = state.get("input", "")
        scene_id = getattr(agent, 'scene_id', 'default')

        # 执行混合检索（向量 + BM25）
        raw_search_results = NavigationSaveService.search_similar_content(
            query=query_text,
            scene_id=scene_id,
            limit=1,
            vector_weight=0.7,  # 向量检索权重
            bm25_weight=0.3     # BM25检索权重
        )

        # 处理搜索结果，找到相似度分数最高的一条数据
        best_result = None
        highest_score = -1
        mcp_list = []
        
        for result in raw_search_results:
            similarity_score = result.get("similarity_score", 0.0)
            if similarity_score > highest_score:
                highest_score = similarity_score
                best_result = result
        
        # 只保存相似度最高的一条结果
        rag_results = []
        if best_result:
            processed_result = {
                "page_name": best_result.get("page_name", "无标题"),  # 页面名称
                "URL": best_result.get("navigation_path", best_result.get("path", "")),  # 导航路径
                "similarity_score": best_result.get("similarity_score", 1.0),  # 相似度分数
            }
            rag_results.append(processed_result)
            # 从最佳结果中获取MCP列表
            mcp_list = best_result.get("mcp_list", [])
            # 添加MCP到agent中
            agent.add_mcp(mcp_list)
            logger.info(f"✅ 找到最佳导航结果，相似度分数: {highest_score}")
        else:
            logger.warning("❌ 未找到有效的导航结果")


        state["rag_results"] = rag_results
        state["mcp_list"] = mcp_list

        # 将RAG查询结果保存到当前执行记忆中
        rag_result_summary = {
            "query": query_text,
            "results_count": len(rag_results),
            "results": rag_results,  # 保存处理后的简化结果
            "success": True,
            "timestamp": datetime.now().isoformat()
        }
        agent._save_result_to_memory("rag", rag_result_summary, state)

    except Exception as e:
        logger.error(f"❌ 导航查询失败: {str(e)}")
        query_text = state.get("input", "")  # 确保变量可用
        rag_error_result = {
            "query": query_text,
            "error": str(e),
            "success": False,
            "timestamp": datetime.now().isoformat()
        }
        agent._save_result_to_memory("rag", rag_error_result, state)

    return state
